//
// Created by china on 25-1-4.
//

#include "ChatServer.h"

ChatServer::ChatServer(EventLoop *loop, const InetAddress &listenAddr, const string &nameArg)
                        : _server(loop,listenAddr,nameArg),_loop(loop){
    //注册连接服务器回调
    _server.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));
    //注册收到消息回调
    _server.setMessageCallback(std::bind(&ChatServer::onMessage,this,_1,_2,_3));
    //设置线程数量
    _server.setThreadNum(4);
    LOG_INFO<<"ip:"<<listenAddr.toIp()<<" , port:"<<listenAddr.toIpPort();
}

void ChatServer::start() {
    LOG_INFO<<"ChatServer::start";
    _server.start();
}

void ChatServer::onConnection(const TcpConnectionPtr &conn) {
    LOG_INFO<<"ChatServer::onConnection";
    //当客户端断开连接
    if(!conn->connected()){
        ChatService::getInstance()->clientCloseExcption(conn);
        conn->shutdown();
    }
}

void ChatServer::onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp time) {
    LOG_INFO << "receive new message:";

    std::string str = buf->retrieveAllAsString();
    size_t posID = str.find("msgID");
    if(posID == std::string::npos){
        LOG_ERROR<<"没有找到 msgID 字段!";
        return ;
    }

    nlohmann::json js = nlohmann::json::parse(str);
    //js["msgid"].get<int>()  js["msgid"]虽然是数字，但还是json类型
    auto msgHandler = ChatService::getInstance()->getHandler((ReqType)js["msgID"].get<int>());
    msgHandler(conn,js,time);
}




